package cn.ll.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ll.po.Role;
import cn.ll.po.RoleDAO;
import cn.ll.service.RoleService;

public class RoleAction extends Action {
	
	public void findAll(HttpServletRequest request,HttpServletResponse response){
		RoleService roleService = (RoleService) this.getApplicationContext().getBean("roleService");
		List<Role> list = roleService.findAll();
		Map map = new HashMap();
		map.put("items", list);
		map.put("success", true);
		rtn(map, request, response);
		return;
	}
	
	/**
	 * 新建角色
	 * @param request
	 * @param response
	 */
	public void save(HttpServletRequest request,HttpServletResponse response){
		String rolename = request.getParameter("rolename");
		if(rolename != null && rolename.length() > 0){
			RoleService roleService = (RoleService) this.getApplicationContext().getBean("roleService");
			Role role = new Role();
			role.setRolename(rolename);
			roleService.save(role);
			
			Map map = new HashMap();
			map.put("success", true);
			rtn(map, request, response);
			return ;
		}
		else{
			Map map = new HashMap();
			map.put("success", false);
			rtn(map, request, response);
			return;
		}
	}
	
	/**
	 * 通过角色ID查询角色
	 * @param request
	 * @param response
	 */
	public void findById(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		if(id != null && id.length() > 0){
			RoleService roleService = (RoleService) this.getApplicationContext().getBean("roleService");
			Role role = roleService.findById(id);
			if(role != null){
				List list = new ArrayList();
				list.add(role);
				
				Map map = new HashMap();
				map.put("success", true);
				map.put("items", list);
				rtn(map, request, response);
				return ;
			}
		}
		
		Map map = new HashMap();
		map.put("success", true);
		rtn(map, request, response);
		return ;
	}
	
	/**
	 * 更新角色
	 * @param request
	 * @param response
	 */
	public void update(HttpServletRequest request,HttpServletResponse response){
		String rolename = request.getParameter("rolename");
		String id = request.getParameter("id");
		if(id != null && id.length() > 0){
			RoleService roleService = (RoleService) this.getApplicationContext().getBean("roleService");
			Role role = roleService.findById(id);
			if(rolename != null && rolename.length() > 0){
				role.setRolename(rolename);
				roleService.update(role);
				
				Map map = new HashMap();
				map.put("success", true);
				rtn(map, request, response);
				return ;
			}
		}
		
		Map map = new HashMap();
		map.put("success", false);
		rtn(map, request, response);
		return ;
	}
	
}
